from rest_framework import serializers
from system.models import Job



class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ['createTime', 'enabled', 'id', 'jobSort', 'name', 'updateBy', 'updateTime']

    createTime = serializers.SerializerMethodField()
    def get_createTime(self, obj):
        return obj.create_time

    jobSort = serializers.SerializerMethodField()
    def get_jobSort(self, obj):
        return obj.job_sort

    updateBy = serializers.SerializerMethodField()
    def get_updateBy(self, obj):
        return obj.update_by

    updateTime = serializers.SerializerMethodField()
    def get_updateTime(self, obj):
        return obj.update_time


class CreateJobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ['enabled', 'jobSort', 'name', 'id']

    jobSort = serializers.CharField(read_only=True)
    def validate(self, attrs):
        print(self.context.get('request').data)
        request = self.context.get('request')
        attrs['job_sort'] = request.data.get('jobSort')
        return attrs

    def create(self, validated_data):
        validated_data['create_by'] = self.context.get('request').user.username
        job = Job.objects.create(**validated_data)
        return job


class UpdateJobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ['enabled', 'id', 'jobSort', 'name',]

    jobSort = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['update_by'] = request.user.username
        attrs['job_sort'] = request.data.get('jobSort')
        return attrs

